<?php

namespace app\backend\controller;

use app\common\controller\Base;
use app\common\service\sys\ClientService;

/**
 * 系统登录-远程(盛筑软件平台)--特叔--业务也在此层
 * @author kaige
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 * @update 2022-04-25
 */
class Loginstore extends Base
{
  // 初始化
  protected function initialize()
  {
    parent::initialize();
  }

  /**
   * 系统登录
   */
  public function index()
  {
    if (request()->isPost()) {
      //接收数据
      $data = input('param.');

      if (empty($data['type'])) {
        return _jerr(1002);
      }

      if (empty($data['username'])) { // 必须
        return _jerr(1002);
      }

      switch ($data['type']) {
        case 'sms':  //短信登录
          if (empty($data['smscode'])) {
            return _jerr(1002);
          }
          if (empty($data['smscaptcha'])) {
            return _jerr(2109);
          }
          if (empty($data['smskey'])) {
            return _jerr(2109);
          }
          break;
        case 'pass': //密码登录
          if (empty($data['password'])) {
            return _jerr(1002);
          }
          if (empty($data['captcha'])) {
            return _jerr(2109);
          }
          break;
      }
      $appid = $this->request->header('Kg-Appid');
      if (empty($appid)) {
        return _jerr(1002);
      }
      // 实时数据
      $clis = new ClientService();
      $app = $clis->getInfoByWhere(['app_id' => $appid]);
      // 是否存在
      if (empty($app)) {
        return _jerr(1004);
      }

      // 云端验证
      $url = config('kaige.authorization_url') . '/api/login/index';
      $result = \util\Curl::curl_request($url, $data, [
        'result' => 'json',
        'method' => 'POST',
      ]);
      return _jok('', $result);
    }
    return _jerr(1000);
  }

  /**
   * 获取云端验证码
   */
  public function yuncode()
  {
    if (request()->isGet()) {
      $url = config('kaige.authorization_url') . '/api/captcha';
      $data = \util\Curl::curl_request($url, [], ['result' => 'json']);
      if ($data) {
        return _jok('', $data);
      }
      return _jerr(1004);
    }
    return _jerr(1000);
  }

  public function yunsms()
  {
    if (request()->isPost()) {
      $data = input('param.');
      if (!isset($data['mobile'])) {
        return _jerr(1002);
      }
      if (!isMobile($data['mobile'])) {
        return _jerr('手机号不正确');
      }
      if (empty($data['smscaptcha'])) {
        return _jerr(2109);
      }
      if (empty($data['smskey'])) {
        return _jerr(2109);
      }
      $url = config('kaige.authorization_url') . '/api/login/sendsms';
      $curl    = new \util\Curl();
      $result = $curl::curl_request($url, $data, ['result' => 'json', 'method' => 'POST']);
      if ($result) {
        return _jok('', $result);
      }
      return _jerr(1004);
    }
    return _jerr(1000);
  }
}
